package com.mytt.upinmama.ui.activity;

import java.util.ArrayList;
import java.util.List;

import org.kymjs.kjframe.ui.BindView;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.mytt.upinmama.bean.ChannelBean;
import com.mytt.upinmama.dao.ChannelDao;
import com.mytt.upinmama.headlinenews.R;
import com.mytt.upinmama.ui.adapter.ClientChannelAdapter;
import com.mytt.upinmama.ui.adapter.OtherChannelAdapter;
import com.mytt.upinmama.ui.view.ClientChannelView;
import com.mytt.upinmama.ui.view.OtherChannelView;

/**
 * 频道管理
 * 
 * @author wenlong.lu
 * 
 *         2015-6-5 下午12:21:37
 */
public class ChannelActivity extends BaseActivity implements OnItemClickListener {
	@BindView(id = R.id.back_iv, click = true)
	private ImageView back_iv;

	@BindView(id = R.id.client_cv)
	private ClientChannelView client_cv;

	@BindView(id = R.id.other_cv)
	private OtherChannelView other_cv;

	@BindView(id = R.id.edit_bt, click = true)
	private Button edit_bt;

	private ClientChannelAdapter adapter;
	private OtherChannelAdapter adapter2;
	private ChannelDao dao;

	// 是否可编辑
	private boolean isDelete = false;

	// 是否在移动，由于这边是动画结束后才进行的数据更替，设置这个限制为了避免操作太频繁造成的数据错乱。
	private boolean isMove = false;
	
	private int page;

	@Override
	public void setRootView() {
		setContentView(R.layout.aty_home_more_title);
	}

	@Override
	public void initWidget() {
		super.initWidget();
		setTitle("频道管理");
		
		Intent intent=getIntent();
		page=intent.getIntExtra("page", 0);
		dao = new ChannelDao(this);
		back_iv.setVisibility(View.VISIBLE);
		if (0 < dao.getmLists().size()) {
			adapter = new ClientChannelAdapter(this, dao.getmLists(),page);
		} else {
			adapter = new ClientChannelAdapter(this, mChannelItem(),page);
		}

		if (0 < dao.getoTherLists().size()) {
			adapter2 = new OtherChannelAdapter(this, dao.getoTherLists());
		} else {
			adapter2 = new OtherChannelAdapter(this, otherChannelItem());
		}

		client_cv.setAdapter(adapter);
		other_cv.setAdapter(adapter2);

		// 设置gridView的item的点击监听
		other_cv.setOnItemClickListener(this);
		client_cv.setOnItemClickListener(this);
	}

	@Override
	public void widgetClick(View v) {
		super.widgetClick(v);

		switch (v.getId()) {
		case R.id.back_iv:
			saveChannel();
			this.setResult(page, getIntent());
			this.finish();
			break;
		case R.id.edit_bt:
			if (isDelete) {
				edit_bt.setText("编辑");
				isDelete = false;
			} else {
				edit_bt.setText("完成");
				isDelete = true;
			}
			adapter.notifyDataSetChanged(isDelete);
			break;

		default:
			break;
		}

	}

	/**
	 * mItem
	 * 
	 * @return
	 */

	private List<ChannelBean> mChannelItem() {
		List<ChannelBean> list = new ArrayList<ChannelBean>();
		for (int i = 0; i < 10; i++) {
			ChannelBean bean = new ChannelBean();
			bean.setId(i);
			bean.setTitle("Item" + i);
			bean.setOrderId(i);
			bean.setSelected(0);
			list.add(bean);
		}
		return list;
	}

	/**
	 * otherItem
	 * 
	 * @return
	 */

	private List<ChannelBean> otherChannelItem() {
		List<ChannelBean> list = new ArrayList<ChannelBean>();
		for (int i = 0; i < 10; i++) {
			ChannelBean bean = new ChannelBean();
			bean.setId(i);
			bean.setTitle("other" + i);
			bean.setOrderId(i);
			bean.setSelected(1);
			list.add(bean);
		}
		return list;
	}

	/** GRIDVIEW对应的ITEM点击监听接口 */
	@Override
	public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) {
		// 如果点击的时候，之前动画还没结束，那么就让点击事件无效
		if (isMove) {
			return;
		}
		switch (parent.getId()) {
		case R.id.client_cv:
			// position为 0，1 的不可以进行任何操作
			if (position != 0 && position != 1) {
				final ImageView moveImageView = getView(view);
				if (moveImageView != null) {
					TextView newTextView = (TextView) view.findViewById(R.id.text_item);
					final int[] startLocation = new int[2];
					newTextView.getLocationInWindow(startLocation);
					if (isDelete) {
						final ChannelBean channel = ((ClientChannelAdapter) parent.getAdapter()).getItem(position);// 获取点击的频道内容
						adapter2.setVisible(false);
						// 添加到最后一个
						adapter2.addItem(channel);
						new Handler().postDelayed(new Runnable() {
							public void run() {
								try {
									int[] endLocation = new int[2];
									// 获取终点的坐标
									other_cv.getChildAt(other_cv.getLastVisiblePosition()).getLocationInWindow(endLocation);
									MoveAnim(moveImageView, startLocation, endLocation, channel, client_cv);
									adapter.setRemove(position);
								} catch (Exception localException) {
								}
							}
						}, 50L);
					}
				}
			}
			break;
		case R.id.other_cv:
			final ImageView moveImageView = getView(view);
			if (moveImageView != null) {
				TextView newTextView = (TextView) view.findViewById(R.id.text_item);
				final int[] startLocation = new int[2];
				newTextView.getLocationInWindow(startLocation);
				final ChannelBean channel = ((OtherChannelAdapter) parent.getAdapter()).getItem(position);
				adapter.setVisible(false);
				// 添加到最后一个
				adapter.addItem(channel);
				new Handler().postDelayed(new Runnable() {
					public void run() {
						try {
							int[] endLocation = new int[2];
							// 获取终点的坐标
							client_cv.getChildAt(client_cv.getLastVisiblePosition()).getLocationInWindow(endLocation);
							MoveAnim(moveImageView, startLocation, endLocation, channel, other_cv);
							adapter2.setRemove(position);
						} catch (Exception localException) {
						}
					}
				}, 50L);
			}
			break;
		default:
			break;
		}
	}

	/**
	 * 点击ITEM移动动画
	 * 
	 * @param moveView
	 * @param startLocation
	 * @param endLocation
	 * @param moveChannel
	 * @param clickGridView
	 */
	private void MoveAnim(View moveView, int[] startLocation, int[] endLocation, final ChannelBean moveChannel, final GridView clickGridView) {
		int[] initLocation = new int[2];
		// 获取传递过来的VIEW的坐标
		moveView.getLocationInWindow(initLocation);
		// 得到要移动的VIEW,并放入对应的容器中
		final ViewGroup moveViewGroup = getMoveViewGroup();
		final View mMoveView = getMoveView(moveViewGroup, moveView, initLocation);
		// 创建移动动画
		TranslateAnimation moveAnimation = new TranslateAnimation(startLocation[0], endLocation[0], startLocation[1], endLocation[1]);
		moveAnimation.setDuration(300L);// 动画时间
		// 动画配置
		AnimationSet moveAnimationSet = new AnimationSet(true);
		moveAnimationSet.setFillAfter(false);// 动画效果执行完毕后，View对象不保留在终止的位置
		moveAnimationSet.addAnimation(moveAnimation);
		mMoveView.startAnimation(moveAnimationSet);
		moveAnimationSet.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
				isMove = true;
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
			}

			@Override
			public void onAnimationEnd(Animation animation) {
				moveViewGroup.removeView(mMoveView);
				// instanceof 方法判断2边实例是不是一样，判断点击的是DragGrid还是other_cv
				if (clickGridView instanceof ClientChannelView) {
					adapter2.setVisible(true);
					adapter2.notifyDataSetChanged();
					adapter.remove();
				} else {
					adapter.setVisible(true);
					adapter.notifyDataSetChanged();
					adapter2.remove();
				}
				isMove = false;
			}
		});
	}

	/**
	 * 获取移动的VIEW，放入对应ViewGroup布局容器
	 * 
	 * @param viewGroup
	 * @param view
	 * @param initLocation
	 * @return
	 */
	private View getMoveView(ViewGroup viewGroup, View view, int[] initLocation) {
		int x = initLocation[0];
		int y = initLocation[1];
		viewGroup.addView(view);
		LinearLayout.LayoutParams mLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		mLayoutParams.leftMargin = x;
		mLayoutParams.topMargin = y;
		view.setLayoutParams(mLayoutParams);
		return view;
	}

	/**
	 * 创建移动的ITEM对应的ViewGroup布局容器
	 */
	private ViewGroup getMoveViewGroup() {
		ViewGroup moveViewGroup = (ViewGroup) getWindow().getDecorView();
		LinearLayout moveLinearLayout = new LinearLayout(this);
		moveLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		moveViewGroup.addView(moveLinearLayout);
		return moveLinearLayout;
	}

	/**
	 * 获取点击的Item的对应View，
	 * 
	 * @param view
	 * @return
	 */
	private ImageView getView(View view) {
		view.destroyDrawingCache();
		view.setDrawingCacheEnabled(true);
		Bitmap cache = Bitmap.createBitmap(view.getDrawingCache());
		view.setDrawingCacheEnabled(false);
		ImageView iv = new ImageView(this);
		iv.setImageBitmap(cache);
		return iv;
	}

	/** 退出时候保存选择后数据库的设置 */
	private void saveChannel() {
		dao.clear();
		dao.saveUserChannel(adapter.getChannnelList());
		dao.saveOtherChannel(adapter2.getChannnelList());
	}

	@Override
	public void onBackPressed() {
		saveChannel();
		super.onBackPressed();
	}
}
